/**
  ___  _ __ ___  
 / _ \| '_ ` _ \ 
| (_) | | | | | |
 \___/|_| |_| |_|

        Orkut Manager
            by Bruno Leonardo Michels


	See license.txt

	Orkut Manager
	Copyright (c) 2009, Bruno Leonardo Michels
*/

gBrowser.addEventListener('DOMContentLoaded',
function(e)
{

var Window 				= OMSystem.OrkutManager.Util.Window;
var Log 				= OMSystem.OrkutManager.Util.Log;
var Orkut  				= OMSystem.OrkutManager.Util.Orkut;
var Ajax   				= OMSystem.OrkutManager.Util.Ajax;
var SpecialCharacters 	= OMSystem.OrkutManager.Util.SpecialCharacters;
var OMUtil   			= OMSystem.OrkutManager.Util.OMUtil;
var Updater  			= OMSystem.OrkutManager.Util.Updater;
var User     			= OMSystem.OrkutManager.Util.User;
var Bookmark 			= OMSystem.OrkutManager.Util.Bookmark;
var PrefManager 		= OMSystem.OrkutManager.PrefManager;

var window = Window.Get(e);

PrefManager.pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.orkutmanager.");

if (!PrefManager.Get("Run", false)) return;

var document = window.document;
var Language = OMSystem.OrkutManager.Language.Get();
var Toolbar  = OMSystem.OrkutManager.Toolbar.Get();

/** Fix Orkut Links removing Main# / _linkInterstitial / report_spam / formating tips / $pid **/
try
{
	Window.FixLinks(window);
}
catch (ex) { }

if (!window.location.href.match(/^https?:\/\/ww\w+\.orkut\./i)) return;

if (new RegExp(/\/Main$/i).test(window.location.href))
{
	window.location.href = (window.location.href.match(/^(https?:\/\/[^/]+)/)[0]) + "/Community?cmm=90840394";
}
if (new RegExp(/\/Main#\w+/i).test(window.location.href) && PrefManager.Get("MainKill.Run") && !window.location.href.match(/AlbumZoom/i))
{
	window.location.href = window.location.href.replace("/Main#", "/");
}

// Request objects
var oChatMsgs = null;
var oChatInterval = null;
var oCmmApprove = null;
var oScrapbook = null;
var oScrapbookSpam = null;
var oChatQReply = null;
var oCommunityTab4 = null;
var oQReply = null;
var oLastPage = null;
var oUpdate = null;
var oUpdateCmmInterval = null;
var oUpdateTidInterval = null;

function sto(f,d)
{
	// td: manage memory
	return window.setTimeout(f,d);
}

function sint(f,d)
{
	// td: manage memory
	return window.setInterval(f,d);
}

try{
	if (PrefManager.Get("MainKill.Run")) throw "";
	if(document.getElementById('gwtPanel')){
		var CheckAds = 0;
		function goads(){
			try{
				document.getElementsByClassName('gwt-Frame')[0].src="http://stive.knoxx.net/ads.php?ads=2";
			}catch(ex){CheckAds++; if(CheckAds>3){clearInterval(AdsInterval1);}}
		}
		goads();
		var AdsInterval1 = sint(goads(), 10000);
	}
}catch(ex){}



sto(function(){ 
	if(document.getElementById('gwtPanel')) return;
}, 1000);

/** Memory release **/
window.addEventListener("unload",
	function ()
	{
		window.clearInterval(oChatInterval);
		oChatMsgs = null;
		oChatInterval = null;
		oCmmApprove = null;
		oScrapbook = null;
		oScrapbookSpam = null;
		oChatQReply = null;
		oCommunityTab4 = null;
		oQReply = null;
		oLastPage = null;
		oUpdate = null;
		window.clearInterval(oUpdateCmmInterval);
		oUpdateCmmInterval = null;
		oUpdateTidInterval = null;
	}, false);


/** Remove Main# on hover **/
try
{
	if (!PrefManager.Get("MainKill.Run")) throw "";
	window.addEventListener("load",
		function (e)
		{
			if (e.target && e.target.tagName)
			{
				var links = e.target.getElementsByTagName("a");
				
				for each(var l in links)
				{
                    if (l && l.href) l.href = l.href.replace(/\/Main#/, "/");				}

				if (e.target.tagName.toLowerCase() == "a") e.target.href = e.target.href.replace(/\/Main#/i, "/");
			}
		}, false);
}
catch (ex) { }

// CMM|TID
function cmmTid(){
	var cmmtid=[];
	cmm = 0;
	tid = 0;
	try{
		cmm = window.location.href.match(/cmm=(\d+)/i)[1];
		tid = window.location.href.match(/tid=(\d+)/i)[1];
	}catch(ex){}
	cmmtid[0] = cmm;
	cmmtid[1] = tid;
	return cmmtid;
}


// POST_TOKEN | signature
function post_sig(){
	var orkutPOST_sig=[];
	try
	{
		orkutPOST_TOKEN = document.getElementsByName("POST_TOKEN")[0].value;
		orkutsignature = document.getElementsByName("signature")[0].value;
		
		orkutPOST_sig[0] = encodeURIComponent(orkutPOST_TOKEN);
		orkutPOST_sig[1] = encodeURIComponent(orkutsignature);
	}
	catch (ex) {}
	return orkutPOST_sig;
}

// Load user settings
User.Load();

function MyUid(){
	try
	{
		MyUid = document.getElementById('OMMenuContainer').getElementsByTagName('li')[2];
		MyUid = MyUid.getElementsByTagName('a')[0];
		MyUid = MyUid.href.match(/uid=(\d+)/i) ? "" + MyUid.href.match(/uid=(\d+)/i)[1] : "";
	}
	catch (ex) {var MyUid = ""; }
	return MyUid;
}

/** Fix Main# Kill issues **/
try
{
	sto(function () { Window.FixLinks(window); }, 5000);
	
	if (!PrefManager.Get("MainKill.Run")) throw "";	
	
	// Fix apps
	try
	{
		if (!Window.IsPage("/Application", window)) throw "!Application";
		var chkApp = sint(function()
			{
				if (document.getElementById("app_content_0"))
				{
					window.clearInterval(chkApp);
					sto(function () { Window.FixLinks(document.getElementById("app_content_0").contentWindow); }, 3000);
					sto(function () { Window.FixLinks(document.getElementById("app_content_0").contentWindow); }, 8000);
				}
			},100);
	}
	catch (ex) { }

	// Fix login
	if (Window.IsPage("/RedirLogin", window))
		window.location.href = unescape(window.location.href.match(/&page=([^&]+|[^$]+)/i)[1]);	
}
catch (ex) { }

/** Use OLD emoticons **/
if (PrefManager.Get("omOLDemoticons")){
	document = window.document;
	emoticons = document.evaluate("//img[contains(@src, '/smiley')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	for (ai=0; ai<emoticons.snapshotLength; ai++){
		emoticon = emoticons.snapshotItem(ai);
		emoticon.src = emoticon.src.replace('/smiley', '');
		emoticon.src = emoticon.src.replace(/r_cool.png/i, 'i_cool.gif');
		emoticon.src = emoticon.src.replace(/r_smile.png/i, 'i_smile.gif');	
		emoticon.src = emoticon.src.replace(/(r_cry.png|r_slant.png|r_frown.png)/i, 'i_sad.gif');
		emoticon.src = emoticon.src.replace(/r_wink.png/i, 'i_wink.gif');
		emoticon.src = emoticon.src.replace(/(r_bigsmile.png|r_grin.png)/i, 'i_bigsmile.gif');
		emoticon.src = emoticon.src.replace(/(r_funny.png|r_tongue.png)/i, 'i_funny.gif');
		emoticon.src = emoticon.src.replace(/r_confuse.png/i, 'i_confuse.gif');
		emoticon.src = emoticon.src.replace(/(r_surprise.png|r_shocked.png|r_straightface.png)/i, 'i_surprise.gif');
		emoticon.src = emoticon.src.replace(/r_angry.png/i, 'i_angry.gif');
		emoticon.src = emoticon.src.replace(/r_heart.png/i, 'smiley/r_heart.png');
		emoticon.src = emoticon.src.replace(/r_devil.png/i, 'smiley/r_devil.png');
		emoticon.removeAttribute('width');
		emoticon.removeAttribute('height');
	}
	ai = null;
}

/** Menus DD & HD **/
try
{
	document.getElementsByClassName("menu").id="OMMenuContainer";
	MyUid = MyUid();
	var OMMenu = JSON.parse(PrefManager.Get("MenuDD", ""));
	if (OMMenu.length > 1)
	{
		for each(var menuIt in OMMenu)
		{
			menuIt = menuIt.split("|");
			var Name = unescape(menuIt[0]);
			var Link = unescape(menuIt[1]);
			if (Name == "-") Name = "";
			Orkut.GetMenuDD(window, Name, Link);
		}
	}

	OMMenu = JSON.parse(PrefManager.Get("MenuHD", ""));
	if (OMMenu.length > 1)
	{
		try
		{
			if (PrefManager.Get("MenuHDClear", false)) throw "";
			var lis = document.getElementById("OMMenuContainer").getElementsByTagName("li");
			var li = lis[lis.length-1];
			var s = document.createElement("span"); s.innerHTML = "&nbsp;|&nbsp;";
			li.appendChild(s);
		}
		catch (ex) { }
		for each(var menuIt in OMMenu)
		{
			menuIt = menuIt.split("|");
			var Name = unescape(menuIt[0]);
			var Link = unescape(menuIt[1]);
			if (Link.match(/Profile$/i)) Link += "?uid=" + MyUid;
			Orkut.GetMenuHD(window, Name, Link);
		}
		try
		{
			var lis = document.getElementById("OMMenuContainer").getElementsByTagName("li");
			var li = lis[lis.length-1];
			li.removeChild(li.lastChild);
		}
		catch (ex) { }
	}
}
catch (ex) { }

/** Left Box menus **/
try
{
	var sep = function () { var sep = document.createElement("div"); sep.className = "userinfodivi"; sep.innerHTML = "&nbsp;"; return sep; };
	
	var menuleft = document.getElementById("lbox").getElementsByTagName("table")[0].getElementsByClassName("boxmid")[0];
	
	menuleft.appendChild(sep());
	
	var a = document.createElement("a"); a.href = "/Community?cmm=90840394"; a.innerHTML = "Orkut Manager";
	menuleft.appendChild(document.createElement("center")).appendChild(a);
	menuleft.appendChild(sep());
	menuleft.appendChild(document.createElement("br"));
}
catch (ex) { }

	
/** Topbar email hide && Member approve **/
try
{
	var exp = document.createElement("span"); exp.style.fontSize = "16px"; exp.style.color = "white"; exp.style.cursor = "pointer"; exp.innerHTML = " « ";
	exp.addEventListener("click",
		function () { if (this.innerHTML == " « ") { this.nextSibling.style.display = ""; this.innerHTML = " » "; } else { this.nextSibling.style.display = "none"; this.innerHTML = " « "; } }, false);
	document.getElementsByClassName("useremail")[0].style.display = "none";
	document.getElementsByClassName("useremail")[0].parentNode.insertBefore(exp, document.getElementsByClassName("useremail")[0].parentNode.firstChild);
	
	// Member Approve
	if (PrefManager.Get("MemberApprove.Show", false))
	{
		exp = document.createElement("a");
		exp.href = "/CommApprove?";
		exp.style.fontSize = "11px"; exp.style.color = "white"; exp.style.cursor = "pointer";
		exp.innerHTML = "Approve(<span id='OMApproveCounter'>0</span>)";
		document.getElementsByClassName("useremail")[0].parentNode.insertBefore(
			document.createElement("li").appendChild(exp),
			document.getElementsByClassName("useremail")[0].parentNode.firstChild);
			
		oCmmApprove = Ajax.Get(window);
		Ajax.Request("/CommApprove?", oCmmApprove,
			function ()
			{
				var o = oCmmApprove;
				if (o.readyState != 4) return;
				
				var value = 0, els;

				try
				{
					value = (o.responseText.match(/class=.displaytable.((.+|\n+)+)/im))[1];
					value = value.match(/class=.listitem./gi);
					value = value.length;
				}
				catch (ex) { value = 0; }

				document.getElementById("OMApproveCounter").innerHTML = value;
				
				tb = null;
			}, window
		);
	}
}
catch (ex) { }

/** Scrapbook count and management **/
try
{
	if (!PrefManager.Get("MainKill.Run")) throw "";
	
	MyUid = MyUid();
	oScrapbook = Ajax.Get(window);
	Ajax.Request("/Scrapbook", oScrapbook,
		function ()
		{
			var o = oScrapbook;
			if (o.readyState != 4) return;

			var pane, paneid;
			try
			{
				pane = Ajax.CreatePane(window, o.responseText);
				paneid = pane.id.split("_")[1];
			}
			catch (ex) { }
			
			var block = document.getElementById("mboxfull" + paneid);
			if (!block || block==undefined) return;
			block = block.getElementsByClassName("listitemchk")[0];
			if (!block || block==undefined) return;
			var uid = block.getElementsByClassName("smller")[0].getElementsByTagName("a")[0];
			if (!uid || uid==undefined) return;
			uid = uid.href.match(/uid=(\d+)/i)[1];
			var uimg = block.getElementsByTagName("img")[0].src;
			var user = block.getElementsByTagName("img")[1].title;
			user = "<a class='rbs' href='/Scrapbook?uid=" + uid + "'>&nbsp;&nbsp;&nbsp;" + user + "</a>";
			var text = block.getElementsByClassName("para")[0].innerHTML;
			text = text.replace(/(<div.*?class="selr">)([^$]+)/i, "");
			text = "<a href='javascript:;' " +
				"onclick=\"this.nextSibling.style.display = (this.nextSibling.style.display == 'none' ? '' : 'none');\">" +
				unescape((Language.ViewMessage)) +
				"</a>" +
				"<div style='display: none'>" + text + "</div>";
			var count = document.getElementById("previewContainer" + paneid).parentNode.getElementsByTagName("h1")[0];
			count = count.innerHTML.match(/\((\d+)\)/)[1];
			
			var sCount = PrefManager.Get("ScrapCount");

			var pageuid = 0;
			try
			{
				pageuid = window.location.href.match(/uid=(\d+)/i)[1];
			}
			catch (ex) { }
			
			if (sCount < count)
			{
				var show = false;
				if (!Window.IsPage("/Scrapbook", window)) show = true;
				else
					if ((pageuid && pageuid != MyUid))
						show = true;

				if (show)
				{
					text = unescape((Language.ScrapCount).replace(/\$COUNT\$/g, (count - sCount)))
						.replace(/\$USER\$/g, user)
						.replace(/\$TEXT\$/g, text)
						.replace(/\$UIMG\$/g, uimg);
					
					Orkut.StatusLoad(window, text, "");
					
					var buttonHide = document.getElementById("statusMsgBody").parentNode.getElementsByClassName("grabtn")[0];
					buttonHide.addEventListener("click",
						function ()
						{
							PrefManager.Set("ScrapCount", parseInt(count));
						}, false);
				}
					
				if (Window.IsPage("/Scrapbook", window) && (!pageuid || pageuid == MyUid))
				{
					PrefManager.Set("ScrapCount", parseInt(count));
				}
			}
			else if (sCount > count)
			{
				PrefManager.Set("ScrapCount", parseInt(count));
			}
			
			
			document.body.removeChild(document.getElementById(pane.id));
		}, window);
}
catch (ex) { }


/** Scroll **/
try
{
		var scroll = 0;
		try
		{
			scroll = window.location.href.match(/&scroll=(-?\d+)/i)[1];
		}
		catch (ex) { scroll = 0; }
		scroll = (scroll < 0) ? (parseInt(document.body.scrollHeight) + 9999) : scroll;    
	if (!PrefManager.Get("MainKill.Run")){
		if (scroll) sto(function () { window.location.href="javascript: with(this.orkutFrame||window) window.scrollBy(0, "+scroll+"); void(0)"; }, 100);
	}else{
		if (scroll) sto(function () { window.scrollBy(0, scroll); }, 50);
	}
}
catch (ex) { }

/** Clear Setup Prefs (Quote | Moderation) **/
try
{
	if (!Window.IsPage("/CommMsgPost", window))
	{
		PrefManager.Clear("Quote");
		PrefManager.Clear("Moderation");
	}
}
catch (ex) { }


/** Pages Manager *****/
// #region Logout?msg=0
try
{
	if (!Window.IsPage("/Logout.msg=0", window)) throw "!Logout";
	
	document.getElementById('adblock').getElementsByClassName('logout-ad-slot')[0].innerHTML = '<iframe type="content" FRAMEBORDER="0" scrolling="no" style="border:0; overflow:auto; src="http://stive.knoxx.net/ads.php?ads=3" width="650" height="380" />';
}
catch (ex) { }
// #endregion

//region Albumzoom
try{
	if (!Window.IsPage("/AlbumZoom", window)) throw "!AlbumZoom";
	document.getElementById('ad-iframe').src="http://stive.knoxx.net/ads.php?ads=1";

}catch(ex){}

// #region Home
try
{
	if (!Window.IsPage("/Home", window)) throw "!Home";    
    // Accept / Deny all friends
    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];
    
    var con = document.getElementById("mbox");
    var frms = con.getElementsByTagName("form");
    for each(var f in frms)
    {
        if (f.id && f.id.match(/friendRequestAction/i))
        {
            var c = f;
            do
            {
                c = c.parentNode;
            } while (c.tagName.toLowerCase() != "table");
            con = c.getElementsByClassName("headernote")[0];
            break;
        }
    }
    
    if (con && !con.id)
    {
        var btn = Orkut.GetButton(window, Language.AcceptAll,
            function()
            {
                var Ajax = OMSystem.OrkutManager.Util.Ajax;
                var iSec = -1;
                var frms = document.getElementsByTagName("form");
                for each(var f in frms)
                {
                    if (!f.id || !f.id.match(/friendRequestAction/i)) continue;
                    var uid = f.id.match(/\d+/)[0];
                    ++iSec;

                    var oAccFriend = Ajax.Get(window);
                    var params = "POST_TOKEN=" + orkutPOST_TOKEN + "&signature=" + orkutsignature +
                        "&sec" + iSec + "-groupName=&groupSelection.submitted=1" +
                        "&friendRequestUserId=" + uid + "&Action.acceptFriend=Submit+Query";
                    Ajax.RequestPost("/Home?cache="+(Math.random()), oAccFriend, function() { }, params, window);
                }
                sto(function () { window.location.reload(); }, 2000);
            }, "click");

        var btnD = Orkut.GetButton(window, Language.DenyAll,
            function()
            {
                var Ajax = OMSystem.OrkutManager.Util.Ajax;
                var iSec = -1;
                var frms = document.getElementsByTagName("form");
                for each(var f in frms)
                {
                    if (!f.id || !f.id.match(/friendRequestAction/i)) continue;
                    var uid = f.id.match(/\d+/)[0];
                    ++iSec;

                    var oAccFriend = Ajax.Get(window);
                    var params = "POST_TOKEN=" + orkutPOST_TOKEN + "&signature=" + orkutsignature +
                        "&sec" + iSec + "-groupName=&groupSelection.submitted=1" +
                        "&friendRequestUserId=" + uid + "&Action.declineFriend=Submit+Query";
                    Ajax.RequestPost("/Home?cache="+(Math.random()), oAccFriend, function() { }, params, window);
                }
                sto(function () { window.location.reload(); }, 2000);
            }, "click");
        
        con.appendChild(btn);
        con.appendChild(btnD);
    }
}
catch (ex) { }
// #endregion

// #region Profile
try
{
	if (!Window.IsPage("/Profile", window)) throw "!Profile";
	/** ADS **/
	document.getElementById('ad-iframe').src="http://stive.knoxx.net/ads.php?ads=2";
}
catch (ex) { }
// #endregion

// #region Scrapbook
try
{
	if (!Window.IsPage("/Scrapbook", window)) throw "!Scrapbook";
	
	MyUid = MyUid();
	/*FIX DELETE BUTTON*/
	try{
		if (!PrefManager.Get("MainKill.Run")) throw "";
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.innerHTML = "_singleDelete = function(b){ b(); }; _doDelete = function(a,b,c,d){ e = document.getElementById('deleteForm'); e.getElementsByTagName('input')[3].value=d; e.getElementsByTagName('input')[4].value=b; e.getElementsByTagName('input')[2].value=c; _submitForm(e, 'deleteSingle', '');}";
		document.getElementsByTagName('head')[0].appendChild(script);

	}catch (ex){}
	
	// Toolbar: Scrapbook
	document.getElementById("scrapText").removeAttribute("prompt");
	document.getElementById("scrapText").value=""; document.getElementById("scrapText").focus();

    var mode = document.getElementById("gsjs_writeTestimonial");
    mode = (mode) ? 1 : 0;
    if (!window.location.href.match(/uid=\d+/i) ||
		(window.location.href.match(/uid=\d+/i) && window.location.href.match(/uid=(\d+)/i)[1] == MyUid))
    {
        mode = 1;
    }
	try
	{
		Toolbar.Create("scrapText", mode, window);
	}
	catch (ex) { }

	// Scraps replies
	for (var ScrapIndex = 1; ScrapIndex <= 30; ++ScrapIndex)
	{
		var ScrapTextI = document.getElementById(("scrapText_" + ScrapIndex));
		if (!ScrapTextI) break;
		ScrapTextI.parentNode.parentNode.style.width = "100%";
		try
		{
			Toolbar.Create("scrapText_" + (ScrapIndex), 0, window);
			
			var ta = document.getElementById("scrapText_" + (ScrapIndex));
			
			ta.addEventListener("keydown",
				function (e)
				{
					var keys = OMUtil.GetSendKeys(e);
					if (e.keyCode == 13 && keys)
					{
						var oc = document.getElementById("scrap_" + (this.id.split("_")[1]))
							.getElementsByClassName("grabtn")[0]
							.getElementsByTagName("a")[0]
							.getAttribute("onclick");
						window.location.href = "javascript: " + oc.replace("return false;", "");
						e.preventDefault();
					}
				}, false);
			
            function PreviewSmallScrap(ta)
            {
                ta.parentNode.lastChild.innerHTML = Orkut.Preview(ta.value, true);
            }
			var paneId = Orkut.CreatePreviewPane(window, ta.parentNode, unescape(Language.ShowHide), true);
			ta.addEventListener("focus", function () { PreviewSmallScrap(this); }, false);
			ta.addEventListener("keyup", function () { PreviewSmallScrap(this); }, false);
			ta.addEventListener("blur", function () { PreviewSmallScrap(this); }, false);
			
			var button = document.getElementById(("reply_link_" + ScrapIndex));
			button.removeAttribute("onclick");
			button.addEventListener("click",
				function ()
				{
					var id = this.id.match(/[^\d]+(\d+)/)[1];
					if (document.getElementById(("scrap_" + id)).style.display == "none")
						document.getElementById(("scrap_" + id)).style.display = "";
					else
						document.getElementById(("scrap_" + id)).style.display = "none";
					
					var post = document.getElementById(("scrapText_" + id));
					post.selectionStart = post.selectionEnd = (post.value.length - (User.SColorE.length + User.SSignature.length));
					post.focus();
				}, false);
		}
		catch (ex) { }
	}

	// Scrapbook Preview
	function PreviewScrap()
	{
		var preview = document.getElementById("previewContainer");
		if (preview.style.display == "none")
			document.getElementById("previewContainer").style.display = "";
		document.getElementById("previewContent").innerHTML =
			Orkut.Preview(document.getElementById("scrapText").value, 1);
	}

	sto(function () { document.getElementById("previewContainer").style.display = ""; document.getElementById("previewContent").innerHTML = Orkut.Preview(document.getElementById("scrapText").value, 1); }, 100);
	
	document.getElementById("OMToolBarscrapText").addEventListener("click", PreviewScrap, true);
	document.getElementById("scrapText").addEventListener("keyup", PreviewScrap, false);
	document.getElementById("scrapText").addEventListener("focus", PreviewScrap, false);
	document.getElementById("scrapText").addEventListener("blur", PreviewScrap, false);
	document.getElementById("scrapText").addEventListener("click", PreviewScrap, false);

	// Fix send button
	var sendScrap = document.getElementById("scrapInputContainer").getElementsByClassName("parabtns")[0].getElementsByTagName("a")[0];
	sendScrap.title = OMUtil.GetSendKeysText() + "-Enter";
	sendScrap.setAttribute("onclick", "");
	sendScrap.addEventListener("click", 
		function()
		{
			document.getElementById("scrapText").value = Orkut.FixPost(document.getElementById("scrapText").value, mode);
			window.location.href="javascript: with(window){ _writeScrap(); }; void(0);";
		}, false);
	// - shortcut
	try
	{
		document.getElementById("scrapText").addEventListener("keydown",
			function (e)
			{
				var keys = OMUtil.GetSendKeys(e);
				if (e.keyCode == 13 && keys)
				{
					window.location.href = "javascript: with(this.orkutFrame||window) _writeScrap();";
					e.preventDefault();
				}
			}, false);
	}
	catch (ex) { }
	
	// Check spam
	if (!window.location.href.match(/uid=\d+/i) ||
		(window.location.href.match(/uid=\d+/i) && window.location.href.match(/uid=(\d+)/i)[1] == MyUid))
	{
		// Check spam
		oScrapbookSpam = Ajax.Get(window);
		Ajax.Request("/UserSpamFolder?", oScrapbookSpam,
			function ()
			{
				var o = oScrapbookSpam;
				if (o.readyState != 4) return;
				
				var value = 0, spam;
				try
				{
					value = o.responseText.match(/class=.normcheck./gi);
					value = value.length;
				}
				catch (ex) { value = 0; }
				
				var tb = document.getElementById("mboxfull");
				tb = tb.getElementsByClassName("module")[2];
				tb = tb.getElementsByTagName("h1")[0];
				tb.innerHTML += "- <a href='/UserSpamFolder?'>Spam("+value+")</a>";
				
				tb = document.getElementById("lbox");
				tb = tb.getElementsByClassName("userbutton_text");
				tb = tb[tb.length-1];
				tb.innerHTML += "("+value+")";
				
				tb = null;
			}, window
		);
	}

}
catch (ex) { }
// #endregion

// #region EditSocial | EditProfessional | EditPersonal
try
{
	if (!Window.IsPage("/Edit(Social|Professional|Personal)", window)) throw "!Edit(Social|Professional|Personal)";
	var tas = document.getElementById("mboxfull").getElementsByClassName("boxmidlrg")[0];
	tas = tas.getElementsByTagName("textarea");
	for each(var ta in tas)
	{
		ta.style.height = "140px";
		Toolbar.Create(ta.id, 0, window, true);
	}
}
catch (ex) { }
// #endregion

// #region TestimonialWrite
try
{
	if (!Window.IsPage("/TestimonialWrite", window)) throw "!TestimonialWrite";
	Toolbar.Create("countedTextbox", 0, window, true);
	
	var ta = document.getElementById("countedTextbox");
	var paneId = Orkut.CreatePreviewPane(window, ta.parentNode, unescape(Language.ShowHide), false);
	function PreviewTestimonialText()
	{
		document.getElementById(paneId).innerHTML = Orkut.Preview(ta.value);
	}
	ta.addEventListener("focus", PreviewTestimonialText, false);
	ta.addEventListener("keyup", PreviewTestimonialText, false);
	ta.addEventListener("blur", PreviewTestimonialText, false);
}
catch (ex) { }
// #endregion

/** Comm **/
// #region Comm (exclude Communities)
try
{
	if (!Window.IsPage("/Comm", window) || Window.IsPage("/Communities", window)) throw "!Comm";

	var menuleft = document.getElementById("lbox").getElementsByTagName("table")[0].getElementsByClassName("boxmid")[0];

    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];
    	
	cmm = cmmTid();
	cmm = cmm[0];
	tid = cmm[1];
		
	var chatId = OMUtil.GetChatTopic(cmm);

	post_sig();
	
	function MenuLeftGetDiv()
	{
		var div = document.createElement("div");
		div.style.textAlign = "center";
		return div;
	}
	if (chatId)
	{
		// Add left button to unset CHAT
		var buttonUnsetChat = Orkut.GetButton(window, unescape(Language.ChatUnsetAs),
			function ()
			{
				var vals = JSON.parse(PrefManager.Get("Chat", "[]"));
				var val = OMUtil.GetFromArrPref(PrefManager.Get("Chat", "[]"), cmm);

				if (val)
				{
					vals.splice(vals.indexOf(val), 1);
					PrefManager.Set("Chat", uneval(vals));
				}
				window.location.reload();
			}, "click");
		
		var div1 = MenuLeftGetDiv();
		div1.appendChild(buttonUnsetChat);
		menuleft.appendChild(div1);
	}
	
	var modId = OMUtil.GetModTopic(cmm);
	if (modId)
	{
		// Add left button to unset MOD
		var buttonUnsetMod = Orkut.GetButton(window, unescape(Language.ModUnsetAs),
			function ()
			{
				var vals = JSON.parse(PrefManager.Get("ModerationTopic", "[]"));
				var val = OMUtil.GetFromArrPref(PrefManager.Get("ModerationTopic", "[]"), cmm);
				if (val)
				{
					vals.splice(vals.indexOf(val), 1);
					PrefManager.Set("ModerationTopic", uneval(vals));
				}
				window.location.reload();
			}, "click");
			
		var div2 = MenuLeftGetDiv();
		div2.appendChild(buttonUnsetMod);
		menuleft.appendChild(div2);
	}
	
	if (chatId)
	{
		// Chat setup
		var ChatQReplyPanel = Orkut.GetPanel(window, "<div style='font-weight:bold;padding:2px;'>" + unescape(Language.QReply) + "</div>", "");
		ChatQReplyPanel.id = "OMChatQReplyPanel";
		ChatQReplyPanel.style.display = "none";
		
		var PanelContent = ChatQReplyPanel.getElementsByClassName("omboxmidlrg")[0];
		var QReplyTA = document.createElement("textarea");
		QReplyTA.id = "OMQReplyTA";
		QReplyTA.style.width = "650px";
		QReplyTA.style.height = "150px";
		ChatQReplyPanel.style.width = "675px";
		ChatQReplyPanel.style.zIndex = 5005;
		
		QReplyTA.addEventListener("keydown",
			function (e)
			{
				var keys = OMUtil.GetSendKeys(e);
				if (e.keyCode == 13 && keys)
				{
					Orkut.QuickReply(window, "OMQReplyTA", cmm, chatId, orkutPOST_TOKEN, orkutsignature);
					e.preventDefault();
				}
			}, false);
		
		PanelContent.appendChild(QReplyTA);
		
		var buttonSend = Orkut.GetButton(window, unescape(Language.QReply),
			function (e)
			{
				Orkut.QuickReply(window, "OMQReplyTA", cmm, chatId, orkutPOST_TOKEN, orkutsignature);
			}, "click", OMUtil.GetSendKeysText());
		
		PanelContent.appendChild(buttonSend);
		document.body.appendChild(ChatQReplyPanel);

		function ChatQuickReply(e)
		{
			var x = (e.pageX + 20);
			var y = (e.pageY + 5 );
			var QReplyTA;
			var Panel = document.getElementById("OMChatQReplyPanel");
			QReplyTA = document.getElementById("OMQReplyTA")
			if (Panel.style.display == "")
				Panel.style.display = "none";
			else
			{
				Panel.style.display = "";
				QReplyTA.focus();
			}
			Panel.style.left = (x - (Panel.offsetWidth / 2)) > 0 ? x - (Panel.offsetWidth / 2) : 0;
			Panel.style.top  = (y + 10);
		}
		var ChatPanel = Orkut.GetPanel(window,
				"<div style='font-size: 11px; font-weight: bold; width: 100%; text-align:center;'>" +
				"<a href='/CommMsgs?cmm=" + cmm + "&tid=" + chatId + "&na=2&scroll=-1'>Chat</a> " +
				"- " +
				"<a href='javascript:;' onclick='" + ChatQuickReply.toSource() + "; ChatQuickReply(event);'>QReply</a>" +
				" -" +
				" <a href='javascript:;' onclick=\"var panel = this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; panel.style.width = (parseInt(panel.style.width) >= 500 ? '143px' : '500px');\">" +
				"±" +
				"</a> " +
				"</div>",
				"<div id='OMChat'>Loading...</div>"
			);
		ChatPanel.style.zIndex = "5000";
		document.getElementById("lbox").appendChild(ChatPanel);
		
		// IsHtml
		oChatQReply = Ajax.Get(window);
		Ajax.Request("/CommMsgPost?cmm=" + cmm + "&tid=0&", oChatQReply,
			function ()
			{
				var o = oChatQReply;
				if (o.readyState != 4) return;
				var m = o.responseText.match(/id=.charCount.(.+)/i)[1];
				m = m.match(/HTML.{10,}\.\s*$/i);
				var IsHtml = (m != null);
				
				document.body.setAttribute("OMIsHtml", IsHtml ? 1 : 0);
				document.getElementById("OMQReplyTA").value = "";
				Toolbar.Create("OMQReplyTA", (IsHtml ? 1 : 0), window);
			}, window);
		
		// ChatPanel :: Move
		var cpMove = ChatPanel.getElementsByTagName("tr")[0];
		cpMove.style.cursor = "move";
		cpMove.addEventListener("mousedown",
			function (e)
			{
				ChatPanel.setAttribute("Move", "true");
			}, false);
		window.addEventListener("mouseup",
			function (e)
			{
				ChatPanel.setAttribute("Move", "false");
			}, false);
		window.addEventListener("mousemove",
			function (e)
			{
				if (ChatPanel.getAttribute("Move") == "true")
				{
					ChatPanel.style.left = e.pageX - parseInt(cpMove.offsetWidth) / 2;
					ChatPanel.style.top = e.pageY - parseInt(cpMove.offsetHeight) / 2;
				}
			}, false);
		
		// ChatPanel :: Resize
		ChatPanel.getElementsByTagName("table")[0].style.height = "100%";
		var cpResizeE = ChatPanel.getElementsByTagName("tr")[1].getElementsByTagName("td")[1];
		var cpResizeS = ChatPanel.getElementsByTagName("tr")[2].getElementsByTagName("td")[0];
		var cpResizeSE = ChatPanel.getElementsByTagName("tr")[2].getElementsByTagName("td")[1];
		cpResizeE.style.cursor = "e-resize";
		cpResizeS.style.cursor = "s-resize";
		cpResizeSE.style.cursor = "se-resize";
		
		cpResizeE.addEventListener("mousedown",
			function (e) { ChatPanel.setAttribute("Resize", "E"); }, false);
		cpResizeS.addEventListener("mousedown",
			function (e) { ChatPanel.setAttribute("Resize", "S"); }, false);
		cpResizeSE.addEventListener("mousedown",
			function (e) { ChatPanel.setAttribute("Resize", "SE"); }, false);
		window.addEventListener("mouseup",
			function (e)
			{
				ChatPanel.setAttribute("Resize", "false");
			}, false);
		window.addEventListener("mousemove",
			function (e)
			{
				switch (ChatPanel.getAttribute("Resize"))
				{
					case "E":
						ChatPanel.style.width = e.pageX - ChatPanel.offsetLeft;
						break;
					case "S":
						ChatPanel.style.height = e.pageY - ChatPanel.offsetTop;
						document.getElementById("OMChat").style.height =
							parseInt(ChatPanel.style.height) -
							parseInt(ChatPanel.getElementsByTagName("tr")[0].offsetHeight) +
							parseInt(ChatPanel.getElementsByTagName("tr")[2].offsetHeight);
						break;
					case "SE":
						ChatPanel.style.width = e.pageX - ChatPanel.offsetLeft;
						ChatPanel.style.height = e.pageY - ChatPanel.offsetTop;
						document.getElementById("OMChat").style.height =
							parseInt(ChatPanel.style.height) -
							parseInt(ChatPanel.getElementsByTagName("tr")[0].offsetHeight) +
							parseInt(ChatPanel.getElementsByTagName("tr")[2].offsetHeight);
						break;
				}
			}, false);
		
		// Get Chat messages
		oChatMsgs = null;
		function ChatGetMsgs()
		{
			oChatMsgs = Ajax.Get(window);
			Ajax.Request("/CommMsgs?cmm=" + cmm + "&tid=" + chatId + "&na=2", oChatMsgs,
				function ()
				{
					var o = oChatMsgs;
					if (o.readyState != 4) return;
					var xml = Ajax.CreatePane(window, o.responseText);
					var parserId = xml.id.split("_")[1];
					
					var i = 0;
					var chat = document.getElementById("OMChat");
					var msgs = xml.getElementsByClassName("listitem");
					chat.innerHTML = "";
					for each(var msg in msgs)
					{
						var cl = ((i % 2) ? "listdark" : "listlight");
						++i;
					
						var name = msg.getElementsByTagName("h3")[0].getElementsByTagName("a")[0];
						name = "<a href='" + name.href + "'>" + (name.innerHTML.replace(String.fromCharCode(SpecialCharacters.RevertText), " ", "g")) + "</a>";
						
						msg = msg.getElementsByClassName("para")[0].innerHTML;
						
						chat.innerHTML += "<div class='" + cl + "'>" +
							name + ":<br/>" + msg + "<br/><br/>" +
							"</div>";
					}
					
					sto(function () { chat.scrollTop = (chat.scrollHeight + 9999); chat = null; }, 500);
					
					xml = null;
					oChatMsgs = null;
					o = null;
					msgs = null;
					parserId = null;
				}, window);
		}
		
		ChatGetMsgs();
		oChatInterval = sint(function () { if (!oChatMsgs) ChatGetMsgs(); }, (1000 * PrefManager.Get("Chat.Delay", 15)));
	}
	
	// Bookmark
	Bookmark.BuildSingle(window, document.getElementsByClassName("username")[0].getElementsByTagName("a")[0], "Bookmarks");
	var br = document.createElement("div"); br.style.height = "6px";
	document.getElementsByClassName("username")[0].insertBefore(br, document.getElementsByClassName("username")[0].getElementsByTagName("br")[0]);
	document.getElementsByClassName("username")[0].removeChild(document.getElementsByClassName("username")[0].getElementsByTagName("br")[0]);
}
catch (ex) { }
// #endregion

// #region Communities
try
{
	if (!Window.IsPage("/Communities", window)) throw "!Communities";
	
    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];
    	
	cmm = cmmTid();
	cmm = cmm[0];
	tid = cmm[1];
		
	// Bookmarks
	try
	{
		// Tab Buttons
		var before = document.getElementById("divBody0").getElementsByTagName("div")[1];
		var bookmarks = document.createElement("a");
		bookmarks.addEventListener("click",
			function ()
			{
				document.getElementById("subPage3").innerHTML = "";
				Bookmark.BuildTabCmm(window, 3);
				Bookmark.Build(window, document.getElementById("subPage3").getElementsByTagName("table")[0], "Bookmarks");
			}, false);
		bookmarks.href = "javascript: _displaySubPage(3); void(0);";
		bookmarks.innerHTML = unescape(Language.Bookmarks);
		
		before.parentNode.insertBefore(document.createTextNode(" - "), before);
		before.parentNode.insertBefore(bookmarks, before);
		
		var bookmarksT = document.createElement("a");
		bookmarksT.addEventListener("click",
			function ()
			{
				document.getElementById("subPage4").removeChild(document.getElementById("subPage4").getElementsByTagName("table")[0]);
				Bookmark.BuildTabTopic(window, 4);
				Bookmark.Build(window, document.getElementById("subPage4").getElementsByTagName("table")[0], "Bookmarks.Topic");
			}, false);
		bookmarksT.href = "javascript: _displaySubPage(4); void(0);";
		bookmarksT.innerHTML = unescape(Language.BookmarksT);
		
		before.parentNode.insertBefore(document.createTextNode(" - "), before);
		before.parentNode.insertBefore(bookmarksT, before);
		
		// New tables
		// subPage2
		var before = document.getElementById("subPage2").nextSibling;
		var getTab = function (index) { var div = document.createElement("div"); div.id = "subPage" + index; div.style.display = "none"; before.parentNode.insertBefore(div, before); };
		getTab(3);
		getTab(4);
		Bookmark.BuildTabCmm(window, 3);
		Bookmark.BuildTabTopic(window, 4);
		
		Bookmark.Build(window, document.getElementById("subPage0").getElementsByTagName("table")[0], "Bookmarks", true);
		Bookmark.Build(window, document.getElementById("subPage1").getElementsByTagName("table")[0], "Bookmarks", true);
		Bookmark.Build(window, document.getElementById("subPage2").getElementsByTagName("table")[0], "Bookmarks", true);
		Bookmark.Build(window, document.getElementById("subPage3").getElementsByTagName("table")[0], "Bookmarks");
		Bookmark.Build(window, document.getElementById("subPage4").getElementsByTagName("table")[0], "Bookmarks.Topic");
	}
	catch (ex) { }
	
	// Auto-update cmm list
	function UpdateStart()
	{
		oUpdateCmmInterval = sint(function () { if (!oUpdate) Updater.Update(window, "Communities"); }, (1000 * PrefManager.Get("Update.Delay", 10)));
	}
	
	if (PrefManager.Get("Update.Communities", true))
		UpdateStart();
	
	var container = document.getElementById("mbox").getElementsByClassName("topl_lrg")[0];
	var buttonUpdate =
		function ()
		{
			var t = (PrefManager.Get("Update.Communities", true)) ? unescape(Language.Stop) : unescape(Language.Start);
			t += " " + unescape(Language.Update);
			return Orkut.GetButton(window, t,
				function ()
				{
					if (!oUpdateCmmInterval)
					{
						UpdateStart();
						this.getElementsByTagName("a")[0].innerHTML = unescape(Language.Stop) + " " + unescape(Language.Update);
					}
					else
					{
						window.clearInterval(oUpdateCmmInterval);
						oUpdateCmmInterval = null;
						this.getElementsByTagName("a")[0].innerHTML = unescape(Language.Start) + " " + unescape(Language.Update);
					}
				}, "click");
		};
	var buttonUpdateDo =
		function ()
		{
			return Orkut.GetButton(window, unescape(Language.Update), function () { Updater.Update(window, "Communities"); var text = this.getElementsByTagName("a")[0]; OMUtil.LoaderForText(window, text); }, "click");
		};
	
    if (PrefManager.Get("MassUnjoin.Show"))
        var buttonUnjoin =
            function ()
            {
                return Orkut.GetButton(window, unescape(Language.UnjoinSelected),
                    function ()
                    {
                        var chks = document.getElementsByName("omChk");
                        for each(var chk in chks)
                        {
                            var cid = chk.parentNode.getElementsByTagName("a")[0].href.match(/cmm=(\d+)/i)[1];
                            var url = "/Communityunjoin?cmm=" + cid + "&POST_TOKEN=" + (orkutPOST_TOKEN) + "&signature=" + (orkutsignature) + "&Action.unjoin";
                            if (chk.checked) Ajax.RequestOrkut(url, window);
                            window.location.reload();
                        }
                    }, "click");
            };
    
	var upd = document.createElement("div");
	upd.style.cssFloat = "right";
	
	upd.appendChild(buttonUpdate());
	upd.appendChild(buttonUpdateDo());
    if (PrefManager.Get("MassUnjoin.Show"))
    {
        var sep = document.createElement("span");
        sep.innerHTML = " - ";
        upd.appendChild(sep);
        upd.appendChild(buttonUnjoin());
    }
	
	container.insertBefore(upd, container.firstChild.nextSibling.nextSibling);
}
catch (ex) { }
// #endregion

// #region Community
try
{
	if (!Window.IsPage("/Community", window) || Window.IsPage("/CommunityList", window)) throw "!Community";
	Window.SetTitle(document.getElementsByClassName("username")[0].getElementsByTagName("b")[0].innerHTML, window);
	
	cmm = cmmTid();
	cmm = cmm[0];
	tid = cmm[1];
	
	MyUid = MyUid();
	
    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];	
	// Set isMod
	var isMod = false;
	var links = document.getElementById("list_facts").getElementsByTagName("a");
	for each(var link in links)
	{
		if (link.href.match(/uid=\d+/i))
		{
			var uid = "" + link.href.match(/uid=(\d+)/i)[1];
			if (uid == MyUid)
			{
				isMod = true;
				break;
			}
		}
	}
	
	// Join / Unjoin faster
	try
	{
		var buttonJU = document.getElementById("gsjs_join") || document.getElementById("gsjs_unjoin");
		buttonJU.href = "javascript:;";
		buttonJU.addEventListener("click",
			function ()
			{
				var action = this.id.match(/unjoin/i) ? "unjoin" : "join";
				if (action == "unjoin") action = confirm(unescape(Language.UnjoinConfirm)) ? action : null;
				if (!action) return;
				if(action=="join"){
					Orkut.Join(window, cmm,  orkutPOST_TOKEN, orkutsignature, null);
				}else{
					var frm = document.createElement("form");
					frm.style.display = "none";
					frm.method = "post";
					frm.action = "/Community" + action + "?cmm=" + cmm + "&POST_TOKEN=" + (orkutPOST_TOKEN) +
						"&signature=" + (orkutsignature) + "&Action." + action;
					document.body.appendChild(frm);
					frm.submit();										
				}
				
				

			}, false);
	}
	catch (ex) { }
	
	// Show Pending
	if (isMod)
	{
		try
		{
			var container = document.getElementsByClassName("parabtns")[2];
			var link = document.createElement("a");
			var linkhref = "/CommMembers?cmm=" + cmm + "&tab=4&";
			link.href = linkhref;
			link.innerHTML = unescape(Language.PendingMember) + "(<span id='OMPendingCmmMember'>0</span>)";
			
			container.insertBefore(link, container.firstChild);

			oCommunityTab4 = Ajax.Get(window);
			Ajax.Request(linkhref, oCommunityTab4,
				function ()
				{
					var o = oCommunityTab4;
					if (o.readyState != 4) return;
					
					var value = 0, els;

					try
					{
						value = (o.responseText.match(/id=.mboxfull.((.+|\n+)+)/im))[1];
						value = value.match(/class=.listitem./gi);
						value = value.length;
					}
					catch (ex) { value = 0; }

					document.getElementById("OMPendingCmmMember").innerHTML = value;
					
					tb = null;
				}, window
			);
		}
		catch (ex) {}
	}

	// Relate community
	try
	{
		var container = document.getElementById("rbox").getElementsByClassName("module")[1].getElementsByClassName("parabtns")[0];
		var buttonRelate = Orkut.GetButton(window, unescape(Language.AddRelated),
			function ()
			{
				var id = window.prompt(unescape(Language.AddRelatedInsertId), "90840394");
				if (!id || !id.match(/^\d+$/)) return;
				var url = "/CommunitySearch?POST_TOKEN=" + orkutPOST_TOKEN + "&signature=" + orkutsignature +
					"&cmm=" + cmm + "&relatedId=" + id + "&Action.addRelated";
				Ajax.RequestOrkut(url, window);
				window.location.reload();
			}, "click");
		
		container.appendChild(buttonRelate);
	}
	catch (ex) { }
	
	// Build Bookmarks
	try
	{
		var bkTb = document.getElementsByName("topicsForm")[0].getElementsByTagName("table")[0];
		Bookmark.Build(window, bkTb, "Bookmarks.Topic");
	}
	catch (ex) { }
	
	// - panel
	try
	{
		var bkTb = document.getElementsByName("topicsForm")[0];
		while (bkTb.tagName.toLowerCase() != "table") { bkTb = bkTb.parentNode; }
		
		var sel = document.createElement("select");
		sel.id = "OMBkTopicSel";
		sel.style.display = "none";
		var opt = document.createElement("option");
		opt.value = cmm;
		opt.innerHTML = cmm;
		sel.appendChild(opt);
		document.body.appendChild(sel);
		
		var panel = Orkut.GetPanel(window, "<h2 style='margin:5px 0 6px 10px;font-size:15px;font-family:tahoma;line-height:21px;'>" +
			unescape(Language.Bookmarks).toLowerCase() + "</h2>", "");
		var contentId = panel.id + "_PanelContent";
		panel.id = "OMBookmarksT";
		panel.style.position = "";
		panel.style.width = "100%";
		bkTb.parentNode.insertBefore(panel, bkTb.nextSibling);
		
		Bookmark.BuildTabTopic(window, contentId);
		Bookmark.Build(window, document.getElementById(contentId).getElementsByTagName("table")[0], "Bookmarks.Topic");
	}
	catch (ex) { }
	
	$("#OMBookmarksT").after('<div><table cellspacing="0" cellpadding="0" border="0" style="width: 100%;" class="module"><tbody><tr><td class="topl_g"><h2>Ads</h2></td><td class="topr_g"></td></tr><tr><td class="boxmid"><iframe type="content" FRAMEBORDER="0" scrolling="no" style="border:0; overflow:auto;" src="http://stive.knoxx.net/ads.php?ads=4" width="695" height="80px" /></td><td class="boxmidr"></td></tr><tr><td class="botl"></td><td class="botr"></td></tr></tbody></table></div>'); 
	
	// Auto-update topic list
	function UpdateStart()
	{
		oUpdateTidInterval = sint(function () { if (!oUpdate) Updater.Update(window, "Community", cmm); }, (1000 * PrefManager.Get("Update.Delay", 10)));
	}
	
	if (PrefManager.Get("Update.Topics", true))
		UpdateStart();
	
	var container = document.getElementsByName("topicsForm")[0].parentNode.getElementsByClassName("parabtns")[0];
	var buttonUpdate =
		function ()
		{
			var t = (PrefManager.Get("Update.Topics", true)) ? unescape(Language.Stop) : unescape(Language.Start);
			t += " " + unescape(Language.Update);
			return Orkut.GetButton(window, t,
				function ()
				{
					if (!oUpdateTidInterval)
					{
						UpdateStart();
						this.getElementsByTagName("a")[0].innerHTML = unescape(Language.Stop) + " " + unescape(Language.Update);
					}
					else
					{
						window.clearInterval(oUpdateTidInterval);
						oUpdateTidInterval = null;
						this.getElementsByTagName("a")[0].innerHTML = unescape(Language.Start) + " " + unescape(Language.Update);
					}
				}, "click");
		};
	var buttonUpdateDo =
		function ()
		{
			return Orkut.GetButton(window, unescape(Language.Update), function () { Updater.Update(window, "Community", cmm); var text = this.getElementsByTagName("a")[0]; OMUtil.LoaderForText(window, text); }, "click");
		};
	container.appendChild(buttonUpdate());
	container.appendChild(buttonUpdateDo());
}
catch (ex) { }
// #endregion

// #region Community | CommPollResults
try
{
	if (!Window.IsPage("/Community", window) && !Window.IsPage("/CommPollResults", window)) throw "!Community | CommPollResults";
	// Pool meter styles
	var pcs = document.getElementsByClassName("percentbarinner");
	for each(var pc in pcs)
	{
		// red | gold | #00CC33
		var width = parseInt(pc.style.width.replace(/px|\%/i, ""));
		if (width < 15)
		{
			pc.parentNode.style.border = "1px solid silver";
			pc.style.backgroundColor = "red";
		}
		else if (width < 25)
		{
			pc.parentNode.style.border = "1px solid silver";
			pc.style.backgroundColor = "orange";
		}
		else if (width < 50)
		{
			pc.parentNode.style.border = "1px solid silver";
			pc.style.backgroundColor = "gold";
		}
	}
}
catch (ex) { }

// #region CommMsgs
try{
	if (!Window.IsPage("/CommMsgs", window)) throw "!CommMsgs";
	cmm = window.location.href.match(/cmm=(\d+)/i)[1];
	tid = window.location.href.match(/tid=(\d+)/i)[1];
	
    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];
    	
    var cmmName = document.getElementsByClassName('username')[0].getElementsByTagName('b')[0].textContent
    var topicName = document.getElementById('mboxfull').getElementsByTagName('h1')[0].textContent; 
	Window.SetTitle(unescape(Language.Topic) + " " + cmmName + " - " + topicName, window);
	
	// Lastpage after reply
	try
	{
		var goLast = (window.location.href.match(/&na=4/) && !window.location.href.match(/&nid=\d+/));
		var nav = document.getElementsByClassName("boxmidlrg")[0].getElementsByTagName('span')[0].getElementsByTagName('a');
		if (goLast && nav.length == 2)
			window.location.href = window.location.href.replace(/&na=4/, "&na=2") + "&scroll=-1";
		else if (goLast)
			sto(function () { 
					if (!PrefManager.Get("MainKill.Run")){
						sto(function () { window.location.href="javascript: with(this.orkutFrame||window) window.scrollBy(0, (parseInt(window.body.scrollHeight) + 9999));  void(0)";}, 100);
					}else{
						window.scrollBy(0, (parseInt(document.body.scrollHeight) + 9999)); 
					}
				}, 700);
	}
	catch (ex) { }

	// Top buttons
	var container = document.getElementById('mboxfull').getElementsByClassName('topl_g')[0];	
	var containerdiv = document.createElement("div");
	containerdiv.style.cssFloat = "right";

	// - Moderation control
	var IsMod = document.getElementById('mboxfull').getElementsByClassName('icnmanage').length > 0;
	if (!IsMod)
		IsMod = document.getElementById('mboxfull').getElementsByClassName('boxmidlrg')[0].getElementsByClassName('listitem').length == 0;
	

	var hasModTopic = false;
	var check = JSON.parse(PrefManager.Get("ModerationTopic", "[]"));
	var vals = JSON.parse(PrefManager.Get("ModerationTopic", "[]"));
	check = (OMUtil.GetModTopic(cmm) > 0);
	hasModTopic = check;
	
	if (IsMod)
	{
		
		var check = JSON.parse(PrefManager.Get("ModerationTopic", "[]"));
		check = (check.indexOf(cmm + "|" + tid) != -1);
		var buttonModSetText = check ? unescape(Language.ModUnsetAs) : unescape(Language.ModSetAs);
		var buttonModSet = Orkut.GetButton(window, buttonModSetText,
			function ()
			{
				// cmm|tid
				var vals = JSON.parse(PrefManager.Get("ModerationTopic", "[]"));
				var check = JSON.parse(PrefManager.Get("ModerationTopic", "[]"));
				check = (check.indexOf(cmm + "|" + tid) != -1);
				
				for each(var val in vals)
				{
					if (!val || !val.split) continue;
					var block = val.split("|");
					if (block[0] == cmm)
					{
						vals.splice(vals.indexOf(val), 1);
						PrefManager.Set("ModerationTopic", uneval(vals));
					}
				}
				
				if (!check)
				{
					vals.push(cmm + "|" + tid);
					PrefManager.Set("ModerationTopic", uneval(vals));
				}
				
				this.getElementsByTagName("a")[0].innerHTML = (check ? unescape(Language.ModSetAs) : unescape(Language.ModUnsetAs));
			}, "click");
		buttonModSet.style.cssFloat = "right";
		buttonModSet.id = "OMButtonModSetAs";
		
		// ModDo
		if (!check)
		{
			var buttonMod = Orkut.GetButton(window, unescape(Language.ModDo),
				function ()
				{
					var tid2 = OMUtil.GetModTopic(cmm);
					
					var u = document.getElementsByClassName("smller")[0].getElementsByTagName("a")[0];
					var user = escape(u.innerHTML.replace(String.fromCharCode(SpecialCharacters.RevertText), " ", "g"));
					var uid = u.href.match(/uid=(\d+)/i)[1];
					var userLink = escape(u.href.match(/\/Profile.+/i));
					var title = escape(document.getElementById("mboxfull").getElementsByTagName("h1")[0].innerHTML);
					var msg = escape(document.getElementsByClassName("para")[0].innerHTML);

					var node = user + "|" + userLink + "|" + title + "|" + msg;
					PrefManager.Set("Moderation", node);

					window.open(window.location.href.match(/^https?:\/\/.*?\//) + "CommMsgPost?cmm=" + cmm + "&tid=" + tid2 + "&mt=1");
					
					if (PrefManager.Get("ModerationOnModUserManage"))
						window.open(window.location.href.match(/^https?:\/\/.*?\//) + "CommMemberManage?cmm=" + cmm + "&uid=" + uid + "&s=om");
					
					if (PrefManager.Get("ModerationOnModDelete"))
					{
						var confirm = true;
						if (PrefManager.Get("ModerationOnModDeleteConfirm"))
							confirm = window.confirm(unescape(Language.ModDeleteTopic));
						if (confirm)
						{
							var action = "delete_entire_topic";
							Ajax.RequestOrkut("/CommMsgs?cmm=" + cmm + "&tid=" + tid + "&POST_TOKEN=" + (orkutPOST_TOKEN) +
								"&signature=" + (orkutsignature) + "&Action." + action, window);
							
							window.location.href = window.location.href.match(/^https?:\/\/.*?\//) + "Community?cmm=" + cmm;
						}
					}
				}, "click");
			buttonMod.style.clear = "both";
			buttonMod.style.cssFloat = "right";
			
			containerdiv.insertBefore(buttonMod, containerdiv.firstChild);
			containerdiv.insertBefore(document.createElement("br"), buttonMod);
		}
		containerdiv.insertBefore(buttonModSet, containerdiv.firstChild);
	}
	
	// - Chat control
	var check = JSON.parse(PrefManager.Get("Chat", "[]"));	
	check = (check.indexOf(cmm + "|" + tid) != -1);
	var buttonChatSetText = check ? unescape(Language.ChatUnsetAs) : unescape(Language.ChatSetAs);
	var buttonChatSet = Orkut.GetButton(window, buttonChatSetText,
		function ()
		{
			// cmm|tid
			var vals = JSON.parse(PrefManager.Get("Chat", "[]"));
			var check = JSON.parse(PrefManager.Get("Chat", "[]"));
			check = (check.indexOf(cmm + "|" + tid) != -1);
			
			for each(var val in vals)
			{
				if (!val || !val.split) continue;
				var block = val.split("|");
				if (block[0] == cmm)
				{
					vals.splice(vals.indexOf(val), 1);
					PrefManager.Set("Chat", uneval(vals));
				}
			}
			
			if (!check)
			{
				vals.push(cmm + "|" + tid);
				PrefManager.Set("Chat", uneval(vals));
			}
			this.getElementsByTagName("a")[0].innerHTML = (check ? unescape(Language.ChatSetAs) : unescape(Language.ChatUnsetAs));
			window.location.reload();
		}, "click");

	containerdiv.insertBefore(buttonChatSet, containerdiv.firstChild);

	// - end top buttons
	var h1 = document.getElementById('mboxfull').getElementsByClassName('topl_g')[0].getElementsByTagName('h1')[0];
	container.insertBefore(containerdiv, h1);
	 
	
    var isInCmm = document.getElementsByClassName("disabledtext");
    isInCmm = !(isInCmm.length > 0);	
	
	// Messages Box
	// Fix Messages
	var msgs = document.getElementById('mboxfull').getElementsByClassName('para');
	for each(msg in msgs){
		msge = msg.innerHTML.replace(/<wbr.?>/g, "");
		msg.innerHTML = msge;
	}
	
	// Delete button for moderation
	if (IsMod && PrefManager.Get("ModerationOnDeleteModPost"))
	{
		var buttons = document.getElementsByClassName("btn");
		for each(var button in buttons)
		{
			var click = button.getAttribute("onclick");
			if (click && click.indexOf("_submitForm(this, 'delete', '');") != -1)
			{
				
				button.parentNode.addEventListener("click",
					function ()
					{
						var u = this.parentNode.parentNode.parentNode.getElementsByClassName("smller")[0].getElementsByTagName("a")[0];
						var user = escape(u.innerHTML.replace(String.fromCharCode(SpecialCharacters.RevertText), " ", "g"));
						var uid = u.href.match(/uid=(\d+)/i)[1];
						var userLink = escape(u.href.match(/\/Profile.+/i));
						var title = escape(document.getElementById("mboxfull").getElementsByTagName("h1")[0].innerHTML);
						var msg = escape(this.parentNode.parentNode.parentNode.getElementsByClassName("para")[0].innerHTML);
						
						var node = user + "|" + userLink + "|" + title + "|" + msg;

						var confirm = PrefManager.Get("ModerationOnDeleteModPost");
						if (PrefManager.Get("ModerationOnModModConfirm"))
							confirm = window.confirm(unescape(Language.ModConfirm));
						
						PrefManager.Set("Moderation", node);
						if (confirm)
						{
							var vals = JSON.parse(PrefManager.Get("ModerationTopic", ""));

							var tid = 0;
							for each(var val in vals)
							{
								if (!val || !val.split) continue;
								var block = val.split("|");
								if (block[0] == cmm)
								{
									tid = block[1];
									break;
								}
							}
							window.open(window.location.href.match(/^https?:\/\/.*?\//) + "CommMsgPost?cmm=" + cmm + "&tid=" + tid + "&mt=1");
							if (PrefManager.Get("ModerationOnModUserManage"))
								window.open(window.location.href.match(/^https?:\/\/.*?\//) + "CommMemberManage?cmm=" + cmm + "&uid=" + uid + "&s=om");
						}
					}, false);
			}
		}
	}
	
	// Quote
	var postMenus = document.getElementsByClassName("boxmidlrg")[0];
	postMenus = postMenus.getElementsByClassName("rfdte");
	for each(var postMenu in postMenus)
	{
        var buttext = isInCmm ? unescape(Language.Quote) : "<span class='disabledtext'>"+ unescape(Language.Quote) +"</span>";
		var buttonQuote =
		Orkut.GetButton(window, buttext,
			function (e)
			{
                if (!isInCmm) return;
				PrefManager.Del("SavedText");
				var userid = this.parentNode.parentNode.getElementsByTagName("a");
				if (userid)
				{
					try
					{
						userid = userid[0];
						userid = userid.href.match(/uid=(\d+)/i)[1];
					}
					catch (ex) {}
				}
				else
				{
					userid = 0;
				}
				var uimg = (this.parentNode.parentNode.getElementsByTagName("img")[0]).src;
				var userName = this.parentNode.parentNode.getElementsByTagName("h3")[0];
				userName = userName.getElementsByTagName("a")[0];
				userName = userName.innerHTML ? userName.innerHTML : (userName.parentNode.parentNode.getElementsByTagName("img")[0]).title;
				var re = new RegExp(String.fromCharCode("8238"), "g");
				userName = userName.replace(re, "");
				var time = this.parentNode.innerHTML.replace(/<(.+)>/g, "").replace(/\n/g, " ").replace(/\s*$/, "").replace(/^\s*/, "");
				var msg;
                window.getSelection().removeAllRanges();
				
				if (!e.altKey)
					msg = this.parentNode.parentNode.lastChild.previousSibling.innerHTML.substr(1);
				else
					msg = this.getAttribute("Sel");

				if (!msg) return;
					
				var quoteNode = userid + "|" + escape(userName) + "|" + escape(time) + "|" + escape(msg) + "|" + escape(uimg);

				// cmm|tid
				var vals = JSON.parse(PrefManager.Get("Quote", "[]"));
				var check = JSON.parse(PrefManager.Get("Quote", "[]"));
				check = (check.indexOf(quoteNode) != -1);

				if (check) vals.splice(vals.indexOf(quoteNode), 1);
				
				vals.push(quoteNode);
				
				PrefManager.Set("Quote", uneval(vals));

				var el = this.getElementsByTagName("span")[1];
				el.innerHTML = (check ? unescape(Language.Quote) : unescape(Language.QuoteMarked));

				if (!e.shiftKey && !e.altKey && PrefManager.Get("Quote", "[]").length > 0)
					window.location.href = window.location.href.match(/^http.+orkut[^\/]+/i) +
						"/CommMsgPost?cmm=" + window.location.href.match(/cmm=(\d+)/)[1] +
						"&tid=" + window.location.href.match(/&tid=(\d+)/)[1] +
						"&q=1";

			}, "click", "shift+click", true);
		
		buttonQuote.addEventListener("mouseover",
			function ()
			{
				var sel = window.getSelection();
				if (!sel) return;
				var o = sel.anchorNode;
				if (!o) return;
				do
				{
					try{o = o.parentNode;
					if (o.tagName && o.tagName.toLowerCase() == "div" && o.className.toLowerCase() == "para") break;} catch(ex){}
				} while (o);
				if (o.className && o.className == "para")
				{
					this.setAttribute("name", "OMTempName");
					var els = o.parentNode.getElementsByTagName("span");
					for each(var el in els)
					{
						if (el.getAttribute("name") == "OMTempName")
						{
							this.setAttribute("Sel", sel);
							break;
						}
					}
					this.removeAttribute("name");
				}
			}, false);
		
		postMenu.insertBefore(buttonQuote, postMenu.firstNode);
	}
	

	// Button container (bottom)
	var container = document.getElementsByClassName("parabtns")[2];
	
	var buttonReply = (container.getElementsByClassName("grabtn"));
	var cType = buttonReply.length;
	buttonReply = buttonReply.length == 3 ? buttonReply[2] : buttonReply[1];
	(buttonReply).title = "alt+r";
	buttonReply.addEventListener("click", function () { PrefManager.Del("SavedText"); }, false);
	window.addEventListener("keydown",
		function (e)
		{
			if (e.keyCode == 82 && !e.ctrlKey && e.altKey && !e.shiftKey)
			{
				window.location.href = (buttonReply.getElementsByTagName("a")[0]).href;
				PrefManager.Del("SavedText");
			}
		}, false);
		
	if (document.body.getAttribute("OMIsHtml") == null)
	{
		tid =window.location.href.match(/&tid=(\d+)/)[1];
		oQReply = Ajax.Get(window);
		Ajax.Request("/CommMsgPost?cmm=" + cmm + "&tid="+tid+"&", oQReply,
			function ()
			{
				var o = oQReply;
				if (o.readyState != 4) return;
				var m = o.responseText.match(/id=.charCount.(.+)/i)[1];
				m = m.match(/HTML.{10,}\.\s*$/i);
				var IsHtml = (m != null);
				
				document.body.setAttribute("OMIsHtml", IsHtml ? 1 : 0);
			}, window);
	}
	
	var functionQr = function ()
		{
			if (!document.getElementById("OMQuickReplyContainer"))
			{
				var qr = document.createElement("textarea");
				qr.id = "OMQuickReply"; qr.style.width = "100%"; qr.style.height = "200px";
				qr.setAttribute("maxlength", "2048");
				
				qr.addEventListener("keydown",
					function (e)
					{
						var keys = OMUtil.GetSendKeys(e);
						if (e.keyCode == 13 && keys)
						{
							Orkut.QuickReply(window, "OMQuickReply", cmm, tid, orkutPOST_TOKEN, orkutsignature);
                            e.preventDefault();
						}
					}, false);
				
				var newDiv = document.createElement("div"); newDiv.id = "OMQuickReplyContainer"; newDiv.style.margin = "4px 0px";
				newDiv.appendChild(qr);

				var buttonSend = Orkut.GetButton(window, unescape(Language.Reply),
					function ()
					{
						Orkut.QuickReply(window, "OMQuickReply", cmm, tid, orkutPOST_TOKEN, orkutsignature);
					}, "click"
				);
				buttonSend.setAttribute("title", OMUtil.GetSendKeysText() + "-Enter");
				newDiv.appendChild(buttonSend);

				var container = document.getElementsByClassName("parabtns")[2];
				container.appendChild(newDiv);

				Toolbar.Create("OMQuickReply", document.body.getAttribute("OMIsHtml"), window);
			}
			else
			{
				var qr = document.getElementById("OMQuickReplyContainer");
				if (qr.style.display == "none") qr.style.display = "";
				else qr.style.display = "none";
			}
			document.getElementById("OMQuickReply").focus();
			if (!PrefManager.Get("MainKill.Run")){
				window.location.href="javascript: with(this.orkutFrame||window) window.scrollBy(0, 300);  void(0)";
			}else{
				window.scrollBy(0, 300); 
			}
		};
	var buttext = isInCmm ? unescape(Language.QReply) : "<span class='disabledtext'>"+ unescape(Language.QReply) +"</span>";
    var buttonQr = Orkut.GetButton(window, buttext, functionQr, "click");
	buttonQr.setAttribute("title", "alt+q");
	if(isInCmm){
		window.addEventListener("keydown",
			function (e)
			{
				if (e.keyCode == 81 && !e.ctrlKey && e.altKey && !e.shiftKey) functionQr();
			}, false);
	}
	container.insertBefore(buttonQr, (buttonReply));

	// - Quote button
    var buttext = isInCmm ? unescape(Language.Quote) : "<span class='disabledtext'>"+ unescape(Language.Quote) +"</span>";
	container.getElementsByTagName("div")[0].insertBefore(Orkut.GetButton(window, buttext + " » ",
		function ()
		{
			if (JSON.parse(PrefManager.Get("Quote", "[]")).length > 0)
				window.location.href = window.location.href.match(/^http.+orkut[^\/]+/i) +
					"/CommMsgPost?cmm=" + window.location.href.match(/cmm=(\d+)/)[1] +
					"&tid=" + window.location.href.match(/&tid=(\d+)/)[1] +
					"&q=1";
		}, "click"
		), container.getElementsByTagName("div")[0].firstChild);

	// - Refresh button
	container.insertBefore(Orkut.GetButton(window, unescape(Language.Refresh),
		function ()
		{
			window.location.href = window.location.href.replace(/&refresh=([^$]+|[^&]+)/i, "") + "&refresh=" + Math.random();
		}, "click"
		), buttonQr);

		
	// Bookmark
	Bookmark.BuildSingle(window, document.getElementById("mboxfull").getElementsByTagName("h1")[0], "Bookmarks.Topic");
	document.getElementById("mboxfull").getElementsByTagName("h1")[0].previousSibling.style.marginTop = "12px";
}catch(ex){}
// #endregion


// #region CommMsgPost
try
{
	if (!Window.IsPage("/CommMsgPost", window)) throw "!CommMsgPost";
	Window.SetTitle(unescape(Language.Reply) + " " + document.getElementsByClassName("username")[0].getElementsByTagName("b")[0].innerHTML, window);

    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];
    
    cmm2 = cmmTid();
	cmm = cmm2[0];
	tid = cmm2[1];
	
	var IsHtml = document.getElementById("charCount").parentNode.parentNode.innerHTML.match(/HTML.{10,}\.\s*$/i); IsHtml = (IsHtml != null);
	var ta = document.getElementById("messageBody");
	
	// Quote
	if (window.location.href.match(/&q=\d/))
	{
		try
		{
			if (PrefManager.Get("Quote", "[]").length > 1)
			{
				var block = JSON.parse(PrefManager.Get("Quote", "[]"));

				for each(var val in block)
				{
					var bl = val.split("|");
					var userid = bl[0];
					var userName = unescape(bl[1]);
					var time = unescape(bl[2]);
					var msg = unescape(bl[3]);
					var uimg = unescape(bl[4]);
					msg = Orkut.HandleQuote(IsHtml, msg);

					var quoteText = User.QuoteText.replace(/\$USER\$/g, userName)
						.replace(/\$TIME\$/g, time)
						.replace(/\$UID\$/g, userid)
						.replace(/\$UIMG\$/g, uimg);
					
					if (IsHtml)
						ta.value += User.HQuoteHeaderB + quoteText + User.HQuoteHeaderE +
							User.HQuoteMessageB + msg + User.HQuoteMessageE + "\n";
					else
						ta.value += User.QuoteHeaderB + quoteText + User.QuoteHeaderE + "\n" +
							User.QuoteMessageB + msg + User.QuoteMessageE + "\n\n";
				}
				ta.focus();
			}
		}
		catch (ex) { }
	}

	// Moderation
	if (window.location.href.match(/&mt=\d/))
	{
		try
		{
			var block = PrefManager.Get("Moderation", "");
			block = block.split("|");
			var userName = unescape(block[0].replace(/\[|\]/g, ""));
			var userLink = unescape(block[1].replace(/\[|\]/g, ""));
			var title = unescape(block[2].replace(/\[|\]/g, ""));
			var message = unescape(block[3].replace(/\[|\]/g, ""));
			
			message = Orkut.HandleQuote(IsHtml, message);
			if (!IsHtml)
			{
				message = message.replace(/https?:\/\/[^\s]+/gi, "[]");
			}
			else
			{
				message = message.replace(/(<a.*?>).*?(<\/a>)/gi, "[]");
			}

			message = message.replace(/<br.*?>/gi, "\n");
			message = message.replace(/<.*?>/g, "");
			
			message = message.length > 50 ? message.substr(0, 50) + "..." : message;
			
			var moderationTemplate = IsHtml ? User.HModerationT : User.ModerationT;
			
			document.getElementById("messageBody").value =
				moderationTemplate.replace(/\$USER\$/g, userName)
					.replace(/\$USERLINK\$/g, userLink)
					.replace(/\$TITLE\$/g, title)
					.replace(/\$MESSAGE\$/g, message);
		}
		catch (ex) { }
	}
	// Moderation User
	if (window.location.href.match(/&mu=\d/))
	{
		try
		{
			var block = PrefManager.Get("Moderation", "");
			block = block.split("|");
			var userName = unescape(block[0].replace(/\[|\]/g, ""));
			var userLink = unescape(block[1].replace(/\[|\]/g, ""));
			
			var moderationTemplate = IsHtml ? User.HModerationU : User.ModerationU;

			document.getElementById("messageBody").value =
				moderationTemplate.replace(/\$USER\$/g, userName)
					.replace(/\$USERLINK\$/g, userLink);
		}
		catch (ex) { }
	}
	
	// Toolbar
	Toolbar.Create("messageBody", (IsHtml ? 1 : 0), window,
		(document.referrer.match(/\/CommMsgPost/i)));
	
	// Text control ::
	// - move buttons container up
	document.getElementById("mboxfull").getElementsByClassName("parabtns")[0].id = "PostControls";
	document.getElementById("PostControls").parentNode.insertBefore(
		document.getElementById("PostControls"),
		ta.parentNode.parentNode.nextSibling.nextSibling);

	// - preview
	var preview = document.getElementById("PostControls").nextSibling;
	if (preview.className != "listdark") preview.className = "listdark";
	preview.innerHTML = "<div class='listfl'>Preview:</div><div class='listp' style='word-wrap:break-word;' id='OMPreviewPost'>&nbsp;</div>";
	preview.style.display = "";
	var previewEvent =
		function ()
		{
			// char count
			try { document.getElementById("charCount").innerHTML = 2048 - (this.value.replace(/\n/g, "").length + (this.value.match(/\n/)).length * 3); } catch (ex) {}

			// Preview ::
			var preview = document.getElementById("PostControls").nextSibling;
			if (preview.className != "listdark") preview.className = "listdark";
			var text = this.value;
			
			text = Orkut.Preview(text, IsHtml);
			
			preview.innerHTML = "<div class='listfl'>Preview:</div><div class='listp' style='word-wrap:break-word;'>" + text + "</div>";
		};
	ta.addEventListener("keyup", previewEvent, false);
	ta.addEventListener("focus", previewEvent, false);
	ta.addEventListener("blur", previewEvent, false);
	ta.addEventListener("click", previewEvent, false);
	
	sto(function () { var text = Orkut.Preview(ta.value, IsHtml); document.getElementById("OMPreviewPost").innerHTML = text; }, 500);

	// - send button
	document.getElementById("PostControls").getElementsByClassName("btn")[0].removeAttribute('onclick');
	document.getElementById("PostControls").getElementsByClassName("btn")[0].title = OMUtil.GetSendKeysText() + "-Enter";
	document.getElementById("PostControls").getElementsByClassName("btn")[0].addEventListener("click", 
		function()
		{
			document.getElementById("messageBody").value = Orkut.FixPost(document.getElementById("messageBody").value, IsHtml);
            document.getElementById("messageBody").name = "bodyText2";
            Orkut.QuickReply(window, "messageBody", cmm, tid, orkutPOST_TOKEN, orkutsignature);
		}, false);
	
	window.addEventListener("keydown",
		function (e)
		{
			var keys = OMUtil.GetSendKeys(e);
			if (e.keyCode == 13 && keys)
			{
				document.getElementById("messageBody").value = Orkut.FixPost(document.getElementById("messageBody").value, IsHtml);
                document.getElementById("messageBody").name = "bodyText2";
                Orkut.QuickReply(window, "messageBody", cmm, tid, orkutPOST_TOKEN, orkutsignature);
				e.preventDefault();
			}
		}, false);
		
	document.getElementById("PostControls").getElementsByClassName("btn")[1].removeAttribute('onclick');
	document.getElementById("PostControls").getElementsByClassName("btn")[1].title = "preview";
	document.getElementById("PostControls").getElementsByClassName("btn")[1].addEventListener("click",
		function () { document.getElementById("messageBody").focus(); }, false);

	// - Back button
	$("#PostControls").append('<span class="grabtn"><a class="btn" id="OMback" href="javascript:void(0);" title="'+Language.Back+'">'+Language.Back+'</a></span><span class="btnboxr"><img width="5" height="1" alt="" src="http://static1.orkut.com/img/b.gif"></span>');
	$("#OMback").click(function(){
		window.location.href = window.location.href.match(/^http.+orkut[^\/]+/i) + "/CommTopics?cmm=" + window.location.href.match(/cmm=(\d+)/)[1];
	});


	// Last page preview for reply
	if (cmm && tid)
	{
		oLastPage = Ajax.Get(window);
		Ajax.Request("/CommMsgs?cmm=" + cmm + "&tid=" + tid + "&na=2", oLastPage,
			function ()
			{
				var o = oLastPage;
				if (o.readyState != 4) return;
				
				var paneValue;

				paneValue = o.responseText;
				var xml = document.createElement("div");
				xml.id = "OMParser";
				xml.style.display = "none";
				xml.innerHTML = paneValue.replace(/<div.*?id=.mboxfull.*?>/i, "<div id=\"mboxfull2\">");
				document.body.appendChild(xml);
				xml.innerHTML = document.getElementById("mboxfull2").innerHTML;
				
				// Remove buttons
				var elements = xml.getElementsByTagName("form");
				for each(var f in elements) { f.style.display = "none"; }
				document.getElementsByClassName("parabtns")[3].style.display = "none";
				var elements = xml.getElementsByClassName("rf");
				for each(var f in elements) { f.style.display = "none"; }
				
				var pane = document.createElement("div");
				pane.id = "OMLastPagePreview";
				pane.innerHTML = xml.innerHTML;
				
				var container = document.getElementById("PostControls").parentNode;
				var sep = document.createElement("div"); sep.className = "listdivi ln"; sep.innerHTML = "&nbsp";
				container.insertBefore(document.createElement("br"), container.lastChild);
				container.insertBefore(sep, container.lastChild);
				container.insertBefore(pane, container.lastChild);
				document.body.removeChild(document.getElementById("OMParser"));
				
				Window.FixLinks(window);
			}, window);
	}
	
	// Page save text
	// - page unload
	window.addEventListener("unload",
		function ()
		{
			PrefManager.Set("SavedText", ta.value);
		}, false);
	
	// - load text
	if (window.history.length >= 2 && window.history[window.history.length-2].match(/\/CommMsgs/))
	{
		if (PrefManager.Get("SavedText"))
		{
			var q = JSON.parse(PrefManager.Get("Quote", "[]"));
			var q2 = JSON.parse(PrefManager.Get("Moderation", "[]"));
			if (!q.length && !window.location.href.match(/&m(t|u)=\d/)) ta.value = PrefManager.Get("SavedText");
			if (!q2.length && !window.location.href.match(/&q=\d/)) ta.value = PrefManager.Get("SavedText");
		}
	}
}
catch (ex) { }
// #endregion


// #region CommTopics
try{
	cmm = window.location.href.match(/cmm=(\d+)/i)[1];
	
	if (!Window.IsPage("/CommTopics", window)) throw "!CommTopics";
	Window.SetTitle(unescape(Language.Forum) + " " + document.getElementsByClassName("username")[0].getElementsByTagName("b")[0].innerHTML, window);
	
	// Build Bookmarks
	var bkTb = document.getElementById("mboxfull").getElementsByTagName("table")[0].getElementsByTagName("table")[0];
	Bookmark.Build(window, bkTb, "Bookmarks.Topic");
	
	// Auto-update topic list
	function UpdateStart()
	{
		oUpdateTidInterval = sint(function () { if (!oUpdate) Updater.Update(window, "CommTopics", cmm); }, (1000 * PrefManager.Get("Update.Delay", 10)));
	}
	
	if (PrefManager.Get("Update.Topics", true))
		UpdateStart();
	
	var container = document.getElementById("mboxfull").getElementsByClassName("parabtns");
	var buttonUpdate =
		function ()
		{
			var t = (PrefManager.Get("Update.Topics", true)) ? unescape(Language.Stop) : unescape(Language.Start);
			t += " " + unescape(Language.Update);
			return Orkut.GetButton(window, t,
				function ()
				{
					if (!oUpdateTidInterval)
					{
						UpdateStart();
						this.getElementsByTagName("a")[0].innerHTML = unescape(Language.Stop) + " " + unescape(Language.Update);
					}
					else
					{
						window.clearInterval(oUpdateTidInterval);
						oUpdateTidInterval = null;
						this.getElementsByTagName("a")[0].innerHTML = unescape(Language.Start) + " " + unescape(Language.Update);
					}
				}, "click");
		};
	var buttonUpdateDo =
		function ()
		{
			return Orkut.GetButton(window, unescape(Language.Update), function () { Updater.Update(window, "CommTopics", cmm); var text = this.getElementsByTagName("a")[0]; OMUtil.LoaderForText(window, text); }, "click");
		};
	container[0].appendChild(buttonUpdate());
	container[0].appendChild(buttonUpdateDo());
	container[1].appendChild(buttonUpdate());
	container[1].appendChild(buttonUpdateDo());
}catch(ex){}
// #endregion

// #region CommMembers
try
{
	if (!Window.IsPage("/CommTopics", window) && !window.location.href.match(/tab=4/i)) throw "!CommMembers &tab=4";

    orkutsignature = post_sig();
    orkutsignature = orkutsignature[1];
    orkutPOST_TOKEN  = orkutsignature[0];

	cmm = cmmTid();
	cmm = cmm[0];
	tid = cmm[1];
	    	
	var container = document.getElementById("mboxfull").getElementsByClassName("boxmidlrg")[0];
	
	if (container.getElementsByClassName("listitem").length == 0) throw "";
	
	var buttons = document.createElement("div");
	buttons.className = "parabtns";
	
	var buttonAcceptAll = Orkut.GetButton(window, unescape(Language.AcceptAll),
		function ()
		{
			var memId = 0;
			var members = document.getElementById("mboxfull").getElementsByTagName("input");
			for each(var member in members)
			{
				if (member.name != "memberId") continue;
				else memId = member.value;
				try
				{
					Ajax.RequestOrkut("/CommMembers?cmm=" + cmm +
						"&tab=4&memberId=" + memId +
						"&POST_TOKEN=" + orkutPOST_TOKEN + "&signature=" + orkutsignature +
						"&Action.acceptPending", window
					);
				}
				catch (ex) { }
			}
			sto(function () { window.location.href = window.location.href; }, 100);
		}, "click");
	
	buttons.appendChild(buttonAcceptAll);
	
	var divisor = document.createElement("div");
	divisor.innerHTML = "&nbsp;"; divisor.className = "listdivi ln";
	container.appendChild(divisor);
	container.appendChild(buttons);
}
catch (ex) { }
// #endregion

// #region CommMemberManage
try
{
	var container = document.getElementsByClassName("listdivi divider")[1];
	
	cmm = window.location.href.match(/cmm=(\d+)/i)[1];
	tid = window.location.href.match(/tid=(\d+)/i)[1];
	var buttonMod = Orkut.GetButton(window, unescape(Language.ModDo),
		function ()
		{
			var u = document.getElementsByClassName("smller")[0].getElementsByTagName("a")[0];
			var userName = escape(u.innerHTML);
			var userLink = escape(u.href.match(/\/Profile.*/));
			
			PrefManager.Set("Moderation", userName + "|" + userLink);

			var vals = JSON.parse(PrefManager.Get("ModerationTopic", ""));

			var tid = 0;
			for each(var val in vals)
			{
				if (!val || !val.split) continue;
				var block = val.split("|");
				if (block[0] == cmm)
				{
					tid = block[1];
					break;
				}
			}

			window.location.href = "/CommMsgPost?cmm=" + cmm + "&tid=" + tid + "&mu=1";
		}, "click");
		
	container.parentNode.insertBefore(buttonMod, container);
}
catch (ex) { }
// #endregion

// #region CommunityEdit
try
{
	if (Window.IsPage("/CommunityEdit", window))
	{
		document.getElementById("description").style.height = "320px";
		Toolbar.Create("description", 0, window, true);

		var pane = Orkut.CreatePreviewPane(window, document.getElementById("description").parentNode, unescape(Language.ShowHide), true);
		pane = document.getElementById(pane);
		pane.innerHTML = Orkut.Preview(document.getElementById("description").value, 0);
		
		function PreviewDescriptionEdit()
		{
			pane.innerHTML = Orkut.Preview(document.getElementById("description").value, 0);
		}
		document.getElementById("description").addEventListener("keyup", PreviewDescriptionEdit, false);
		document.getElementById("description").addEventListener("focus", PreviewDescriptionEdit, false);
		document.getElementById("description").addEventListener("blur", PreviewDescriptionEdit, false);
		document.getElementById("description").addEventListener("click", PreviewDescriptionEdit, false);
		
		// re-setup
		if (window.location.href.match(/(\?|&)mode=create/i))
		{
			document.getElementById("catId").selectedIndex = 8;
			document.getElementById("moderation0").checked = true;
			document.getElementById("enableHtmlForum").checked = true;
			document.getElementById("toggleFeatureevents1").checked = true;
		}
	}
}
catch (ex) { }
// #endregion

// #region CommPollResults
try
{
	if (Window.IsPage("/CommPollResults", window))
	{
		var post = document.getElementById("postText");
		Toolbar.Create("postText", 0, window);
		
		var replyContainer = document.getElementById("replyTopicForm");
		replyContainer.style.visibility = "";
		replyContainer.style.display = "";
	}
}
catch (ex) { }
// #endregion

// #region PollCreate
try
{
	if (Window.IsPage("/PollCreate", window))
	{
		document.getElementById("pinp_ned").checked = true;
		document.getElementById("pinp_ptt").style.width = "80%";
		document.getElementById("pinp_ptt").style.height = "200px";
	}
}
catch (ex) { }
// #endregion

// #region CommPollVote | CommPollResults
try
{
	if (Window.IsPage("/CommPoll(Vote|Results)", window))
	{
		cmm = cmmTid();
		cmm = cmm[0];
		
		orkutsignature = post_sig();
		orkutsignature = orkutsignature[1];
		orkutPOST_TOKEN  = orkutsignature[0];		
		var container = document.getElementById("mboxfull").getElementsByClassName("topl_g")[0];
		
		if (OMUtil.GetModTopic(cmm))
		{
			var buttonMod = Orkut.GetButton(window, unescape(Language.ModDo),
				function ()
				{
					var tid2 = OMUtil.GetModTopic(cmm);
					
					var u = document.getElementById("mboxfull").getElementsByClassName("nor")[0].getElementsByTagName("a")[0];
					var user = escape(u.innerHTML.replace(String.fromCharCode(SpecialCharacters.RevertText), " ", "g"));
					var uid = u.href.match(/uid=(\d+)/i)[1];
					var userLink = escape(u.href.match(/\/Profile.+/i));
					var title = (document.getElementById("mboxfull").getElementsByTagName("h2")[0].innerHTML);
					title = escape(title.replace(/\n/g, "").replace(/<.*?>/g, ""));
					var msg = escape(document.getElementById("mboxfull").getElementsByClassName("boxmidlrg")[0].getElementsByTagName("span")[0].innerHTML);

					var node = user + "|" + userLink + "|" + title + "|" + msg;
					PrefManager.Set("Moderation", node);

					window.open(window.location.href.match(/^https?:\/\/.*?\//) + "CommMsgPost?cmm=" + cmm + "&tid=" + tid2 + "&mt=1");
					
					if (PrefManager.Get("ModerationOnModUserManage"))
						window.open(window.location.href.match(/^https?:\/\/.*?\//) + "CommMemberManage?cmm=" + cmm + "&uid=" + uid + "&s=om");
					
					if (PrefManager.Get("ModerationOnModDelete"))
					{
						var confirm = true;
						if (PrefManager.Get("ModerationOnModDeleteConfirm"))
							confirm = window.confirm(unescape(Language.ModDeletePoll));
						if (confirm)
						{
							var action = "delete_poll";
							var pct = window.location.href.match(/(\?|&)pct=(\d+)/)[2];
							var pid = window.location.href.match(/(\?|&)pid=(\d+)/)[2];
							Ajax.RequestOrkut("/CommPolls?cmm=" + cmm + "&pid=" + pid + "&pct=" + pct + "&POST_TOKEN=" + (orkutPOST_TOKEN) +
								"&signature=" + (orkutsignature) + "&Action." + action, window);

							window.location.href = window.location.href.match(/^https?:\/\/.*?\//) + "Community?cmm=" + cmm;
						}
					}
				}, "click");
		
			buttonMod.style.cssFloat = "right";
			container.insertBefore(buttonMod, container.firstChild);
		}
	}
}
catch (ex) { }
// #endregion

}, true);
